// Copyright (c) 2021 Presto Labs Pte. Ltd.
// Author: leon

#pragma once

#include <memory>
#include <optional>
#include <regex>
#include <string>
#include <string_view>
#include <vector>

#include "coin2/base/string_util.h"
#include "coin2/exchange/base/symbology/spot_product.h"
#include "coin2/exchange/base/symbology/util.h"
#include "coin2/exchange/phemex/symbology/currency.h"

namespace coin2::exchange::phemex::symbology {

class PhemexProduct : public base::symbology::SpotProduct<PhemexCurrency, PhemexProduct>,
                      public base::symbology::ProductFromStrMixin<PhemexProduct> {
 public:
  typedef SpotProduct<PhemexCurrency, PhemexProduct> BaseProduct;

  PhemexProduct(const PhemexCurrency& base, const PhemexCurrency& quote)
      : SpotProduct(
            base,
            quote,
            ToPhemexNativeProduct(base, quote),
            ToPhemexNativeProduct(base, quote),
            base::market::ExchangeType::Phemex) {}

 public:
  static std::unique_ptr<PhemexProduct> FromNativeStrImpl(
      const std::string& native_product,
      int64_t resolve_timestamp) {
    std::unique_ptr<PhemexCurrency> base_ptr;
    std::unique_ptr<PhemexCurrency> quote_ptr;
    bool success =
        ParsePhemexNativeProduct(native_product, resolve_timestamp, &base_ptr, &quote_ptr);
    if (success) {
      return std::make_unique<PhemexProduct>(*base_ptr, *quote_ptr);
    } else {
      return {};
    }
  }

 private:
  static bool ParsePhemexNativeProduct(
      const std::string& product_str,
      int64_t resolve_timestamp,
      std::unique_ptr<PhemexCurrency>* base_ptr,
      std::unique_ptr<PhemexCurrency>* quote_ptr) {
    static const std::regex reg("(s)([A-Z0-9]{1,12})(BRZ|TRY|USDC|USDT)");
    std::smatch match;
    bool res = std::regex_match(product_str, match, reg);
    if (!res) {
      return false;
    }

    std::string native_base = match[2];
    std::string native_quote = match[3];

    *base_ptr = PhemexCurrency::FromNativeStrNoThrow(native_base, resolve_timestamp);
    *quote_ptr = PhemexCurrency::FromNativeStrNoThrow(native_quote, resolve_timestamp);
    return true;
  }

  static std::string ToPhemexNativeProduct(
      const PhemexCurrency& base,
      const PhemexCurrency& quote) {
    using base::market::MarketType;
    std::stringstream ss;
    ss << "s" << base.native_currency(MarketType::Spot) << quote.native_currency(MarketType::Spot);
    return ss.str();
  }
};

}  // namespace coin2::exchange::phemex::symbology
